package com.tierstall.client.presenter;



import com.google.gwt.event.shared.HandlerManager;

import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasWidgets;




import com.tierstall.client.event.LoginEvent;
import com.tierstall.client.service.UsersServiceAsync;
import com.tierstall.client.service.WebServices;
import com.tierstall.client.view.LoginView;
import com.tierstall.shared.Logger;
import com.tierstall.shared.Page;
import com.tierstall.shared.UserDTO;

public class LoginPresenter implements Presenter, LoginView.Display {

	private final WebServices rpcService;
	private final HandlerManager eventBus;
	private final LoginView view;


	// private boolean isUpdating = false;

	public LoginPresenter(WebServices rpcServices,
			HandlerManager eventBus, LoginView view) {
		this.rpcService = rpcServices;
		this.eventBus = eventBus;
		this.view = view;
		this.view.setPresenter(this);
	}

	public void go(final HasWidgets container) {
		container.clear();
		container.add(view.asWidget());
	}

	@Override
	public void onLoginClicked(String username, String password, final boolean save_session) {
		rpcService.getRpcSessionService().loginRequest(username, password, new AsyncCallback<String>() {
  			@Override
			public void onSuccess(String session) {
				if (session.equals("not existing")){
					view.enableUsernameInfo("Falscher Benutzername!");
				} else if (session.equals("wrong password")){
					view.enablePasswordInfo("Falsches Passwort!");
				} else { // pw + username correct
					getLoggedInUser(save_session, session);
					
				}
				
			}
		      public void onFailure(Throwable caught) {
			        Window.alert("Error retrieving contact");
			      }
		    });
	}
	
	private void getLoggedInUser(final boolean save_session, final String session) {
		rpcService.getRpcSessionService().getLoggedInUser(session,
				new AsyncCallback<UserDTO>() {
					@Override
					public void onSuccess(UserDTO user) {
						if (user != null) {
							Logger.CLIENT_INFO("currentUser: "
									+ (user.getUsername())+" with Session ID: " + session);
							eventBus.fireEvent(new LoginEvent(save_session, session, user));
						}
						else
							Logger.CLIENT_INFO("currentUser is null");
						
					}

					public void onFailure(Throwable caught) {
						Window.alert("Could not get Logged-in User!");
						History.newItem(Page.LOGIN.id());
					}
				});
	}

}
